from __future__ import annotations
import json
import os
from pathlib import Path

class File:
    path:str
    
    def __init__(self,path:str) -> None:
        self.path=path

    @property
    def name(self):
        return os.path.basename(self.path)
    
    def toDict(self):
        return {"path":self.path,"name":self.name}

class Dir:
    path:str
    sub_dirs:list[Dir]
    files:list[File]

    def __init__(self,path) -> None:
        self.path=path
        self.sub_dirs=[]
        self.files=[]
        self._walk()
    
    def _walk(self):
        cur_dir=Path(self.path)
        if not cur_dir.exists():
            raise Exception(f"{self.path} does not exist!")
        if not cur_dir.is_dir():
            raise Exception(f"{self.path} is not a directory!")
        
        for path in cur_dir.glob("*"):
            cur_path=Path(path)
            if cur_path.is_file():
                file=File(str(path))
                self.files.append(file)
            elif cur_path.is_dir():
                sub_dir=Dir(str(path))
                self.sub_dirs.append(sub_dir)
    
    @property
    def name(self):
        return os.path.basename(self.path)

    def toDict(self):
        return {
            "name":self.name,
            "path":self.path,
            "sub_dirs":[d.toDict() for d in self.sub_dirs],
            "files":[f.toDict() for f in self.files],
        }




if __name__ == "__main__":
    dir_path=r"E:\我的文档\sbwbooks\编程文档"
    root_dir=Dir(dir_path)
    _dict=root_dir.toDict()
    with open('root.json','w',encoding='utf8') as f:
        json.dump(_dict,f,indent=2,ensure_ascii=False)